/*
 * TODO: Enter copyright statement here.
 */
package com.googlecode.wcbunittests.helloworld.propertyeditor;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.text.ParseException;

/**
 * This property editor can convert a String to a Calendar and vice versa.
 */
public class CalendarPropertyEditor extends PropertyEditorSupport {
    // Static logger for this class
    private static final Logger LOG = Logger.getLogger(CalendarPropertyEditor.class.getName());

    // The pattern used when the date is represented as String, default is dd/MM/yyyy
    private static final String DEFAULT_PATTERN = "dd/MM/yyyy";

    // The date formatter
    private SimpleDateFormat myFormatter;

    /**
     * Constructor. Creates a new calendar proeprty editor with the default pattern, which is dd/MM/yyyy.
     */
    public CalendarPropertyEditor() {
        myFormatter = new SimpleDateFormat(DEFAULT_PATTERN);
    }

    /**
     * Constructor. Creates a new calendar proeprty editor with the specified pattern.
     * @param pattern The pattern used when the date is represented as String
     */
    public CalendarPropertyEditor(String pattern) {
       myFormatter = new SimpleDateFormat(pattern);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getAsText() {
        Object value = getValue();
        if (value == null || !Calendar.class.isAssignableFrom(value.getClass())) {
            return null;
        }
        return myFormatter.format(((Calendar) value).getTime());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setAsText(String text) {
        Calendar newValue = null;
        if ((text != null) && (text.trim().length() > 0)) {
            newValue = Calendar.getInstance();
            try {
                newValue.setTime(myFormatter.parse(text));
            } catch(ParseException e) {
                // Log the parse error
                LOG.log(Level.WARNING, "Could not convert \"" + text + "\" to a date.", e);
            }
        }
        setValue(newValue);
    }
}
